<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">

      <el-table :data="form.dealMajorClientList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('客户名称')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('客户名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealMajorClientList.' + scope.$index + '.customerName'" :rules="dealMajorClientListRules.customerName">
              <el-input v-model="scope.row.customerName" :placeholder="$t('客户名称')" show-word-limit maxlength="25" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('销售占比(%)')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('销售占比(%)') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealMajorClientList.' + scope.$index + '.proportionOfSales'" :rules="dealMajorClientListRules.proportionOfSales">
              <Ratio
                v-model="scope.row.proportionOfSales"
                :placeholder="$t('销售占比(%)')"
                show-word-limit
                :max="100"
                :min="0"
                :controls="false"
                :precision="2"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('订单金额') + $t('金额单位')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('订单金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealMajorClientList.' + scope.$index + '.orderAmount'" :rules="dealMajorClientListRules.orderAmount">
              <Money v-model="scope.row.orderAmount" unit="w" :placeholder="$t('订单金额')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" align="center">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('备注') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealMajorClientList.' + scope.$index + '.remark'" :rules="dealMajorClientListRules.remark">
              <el-input v-model="scope.row.remark" type="textarea" class="fileTextarea" :placeholder="$t('备注')" show-word-limit maxlength="1000" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['deal:majorclient:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button v-hasPermi="['deal:majorclient:edit']" type="primary" icon="el-icon-plus" size="mini" @click="addHandle">{{ $t("添加") }}</el-button>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="deal:majorclient" />
    </div>
  </div>
</template>

<script>
    import { saveDealMajorClient, getByCompanyIdAndYear, delDealMajorClient } from '@/api/deal/majorclient/dealMajorClient.js'
    export default {
        data() {
            const requiredData = (rule, value, callback) => {
              if (rule.field.indexOf('customerName') !== -1) {
                value = this.form.dealMajorClientList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].customerName
              }
              if (rule.field.indexOf('proportionOfSales') !== -1) {
                value = this.form.dealMajorClientList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].proportionOfSales
              }
              if (rule.field.indexOf('orderAmount') !== -1) {
                value = this.form.dealMajorClientList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].orderAmount
              }
              if (value === undefined || value === '' || value === null) {
                callback(new Error(this.$t('必填信息')))
              } else {
                callback()
              }
            }
            return {
                // 表单参数
                form: {},
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {},
                dealMajorClientListRules: {
                  customerName: [{ required: true, validator: requiredData, trigger: ['blur', 'change'] }],
                  proportionOfSales: [{ required: true, validator: requiredData, trigger: ['blur', 'change'] }],
                  orderAmount: [{ required: true, validator: requiredData, trigger: ['blur', 'change'] }]
                },
                parentPageYear: ''
            }
        },
        created() {
          // this.init()
        },
        methods: {
            // 初始化数据
            init() {
              this.loading = true
              getByCompanyIdAndYear(this.$route.query.companyId, this.parentPageYear).then(response => {
                this.form.dealMajorClientList = response.data
                this.loading = false
              })
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                companyId: this.$route.query.companyId,
                year: undefined,
                customerName: undefined,
                proportionOfSales: undefined,
                orderAmount: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                dealMajorClientList: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    var yearFlag = false
                    if (this.parentPageYear === '') {
                      this.$message({
                        showClose: true,
                        message: this.$t('获取年份异常,请刷新重试!'),
                        type: 'error'
                      })
                    } else {
                      this.form.year = this.parentPageYear
                      yearFlag = true
                    }
                    if (valid && yearFlag) {
                        this.loading = true
                        this.form.companyId = this.$route.query.companyId
                        saveDealMajorClient(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                              if (this.$route.query.companyId) {
                                this.$store.dispatch('bussRisk/UPDATE_BUSS_RISK_COUNT', { id: this.$route.query.companyId })
                              }
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
            },
            addHandle() {
              const row = {
                id: '',
                customerName: '',
                proportionOfSales: '',
                orderAmount: '',
                remark: ''
              }
              if (!(this.form.dealMajorClientList instanceof Array)) {
                this.$set(this.form, 'dealMajorClientList', [])
              }
              this.$nextTick(() => {
                this.form.dealMajorClientList.push(row)
              })
            },
            delHandle(index, row) {
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(function() {
                    return delDealMajorClient(id)
                  }).then(() => {
                  this.form.dealMajorClientList.splice(index, 1)
                  this.$forceUpdate()
                  return this.msgSuccess(this.$t('删除成功'))
                })
                  .catch(function() {})
              } else {
                this.form.dealMajorClientList.splice(index, 1)
                this.$forceUpdate()
              }
            }
        }
    }
</script>
